import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Random;

public class FruitNinjaGame extends JFrame {
    private GamePanel gamePanel;

    public FruitNinjaGame() {
        setTitle("Java多线程切水果游戏 - 30秒挑战");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        gamePanel = new GamePanel();
        add(gamePanel);

        setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(FruitNinjaGame::new);
    }
}

class GamePanel extends JPanel {
    private ArrayList<Fruit> fruits = new ArrayList<>();
    private Random random = new Random();
    private int score = 0;
    private long lastFruitTime = 0;
    private boolean gameStarted = false;
    private boolean gameOver = false;
    private long startTime;
    private final int GAME_DURATION = 30000; // 30秒游戏时间

    public GamePanel() {
        setBackground(new Color(135, 206, 235)); // 天空蓝背景

        addMouseMotionListener(new MouseAdapter() {
            @Override
            public void mouseMoved(MouseEvent e) {
                checkSlice(e.getX(), e.getY());
            }

            @Override
            public void mouseDragged(MouseEvent e) {
                checkSlice(e.getX(), e.getY());
            }
        });

        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (!gameStarted || gameOver) {
                    startGame();
                }
            }
        });

        // 游戏主循环线程
        new Thread(() -> {
            while (true) {
                if (gameStarted && !gameOver) {
                    update();
                    repaint();

                    // 检查游戏时间是否结束
                    if (System.currentTimeMillis() - startTime > GAME_DURATION) {
                        gameOver = true;
                    }
                }

                try {
                    Thread.sleep(16); // 约60FPS
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void startGame() {
        gameStarted = true;
        gameOver = false;
        score = 0;
        fruits.clear();
        startTime = System.currentTimeMillis();
    }

    private void checkSlice(int x, int y) {
        if (!gameStarted || gameOver) return;

        for (Fruit fruit : new ArrayList<>(fruits)) {
            if (fruit.isSliced()) continue;

            if (fruit.contains(x, y)) {
                fruit.slice();
                score += fruit.isBomb() ? -30 : 10;
            }
        }
    }

    public void update() {
        // 随机生成水果或炸弹
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastFruitTime > 500) { // 每0.5秒可能生成一个
            if (random.nextDouble() < 0.7) { // 70%概率生成
                boolean isBomb = random.nextDouble() < 0.15; // 15%概率是炸弹
                fruits.add(new Fruit(
                        random.nextInt(getWidth() - 50),
                        getHeight(),
                        isBomb,
                        this
                ));
            }
            lastFruitTime = currentTime;
        }

        // 更新水果位置
        for (Fruit fruit : new ArrayList<>(fruits)) {
            fruit.update();

            // 移除超出屏幕或已被切开的水果
            if (fruit.isOutOfScreen() || (fruit.isSliced() && fruit.getAlpha() <= 0)) {
                fruits.remove(fruit);
                fruit.stopThread();
            }
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        // 绘制游戏信息
        g.setColor(Color.BLACK);
        g.setFont(new Font("Arial", Font.BOLD, 24));
        g.drawString("分数: " + score, 20, 30);

        long elapsedTime = gameStarted ? System.currentTimeMillis() - startTime : 0;
        long remainingTime = Math.max(0, (GAME_DURATION - elapsedTime) / 1000);
        g.drawString("剩余时间: " + remainingTime + "秒", 20, 60);

        // 绘制开始/结束界面
        if (!gameStarted || gameOver) {
            g.setColor(new Color(0, 0, 0, 150));
            g.fillRect(0, 0, getWidth(), getHeight());

            g.setColor(Color.WHITE);
            g.setFont(new Font("Arial", Font.BOLD, 36));

            String message;
            if (!gameStarted) {
                message = "点击开始游戏";
            } else {
                message = "游戏结束! 最终分数: " + score;
            }

            int messageWidth = g.getFontMetrics().stringWidth(message);
            g.drawString(message, getWidth()/2 - messageWidth/2, getHeight()/2);

            g.setFont(new Font("Arial", Font.PLAIN, 24));
            g.drawString("点击重新开始", getWidth()/2 - 70, getHeight()/2 + 50);
        }

        // 绘制所有水果
        for (Fruit fruit : fruits) {
            fruit.draw(g);
        }
    }
}

class Fruit {
    private int x, y;
    private int size;
    private int speed;
    private boolean sliced = false;
    private boolean isBomb;
    private int alpha = 255; // 用于淡出效果
    private Color color;
    private GamePanel panel;
    private Thread movementThread;

    public Fruit(int x, int y, boolean isBomb, GamePanel panel) {
        this.x = x;
        this.y = y;
        this.panel = panel;
        this.isBomb = isBomb;
        this.size = 40 + new Random().nextInt(20);
        this.speed = 2 + new Random().nextInt(5);

        if (isBomb) {
            color = Color.BLACK;
        } else {
            // 随机水果颜色
            int type = new Random().nextInt(3);
            switch (type) {
                case 0: color = new Color(255, 99, 71); break; // 番茄色
                case 1: color = new Color(50, 205, 50); break; // 酸橙绿
                default: color = new Color(255, 215, 0); // 金色
            }
        }

        // 创建并启动移动线程
        movementThread = new Thread(() -> {
            while (!isOutOfScreen() && (!sliced || alpha > 0)) {
                try {
                    Thread.sleep(30);
                } catch (InterruptedException e) {
                    break;
                }

                SwingUtilities.invokeLater(this::update);
            }
        });
        movementThread.start();
    }

    public void update() {
        if (!sliced) {
            y -= speed;
        } else {
            alpha -= 5;
        }
    }

    public void draw(Graphics g) {
        if (sliced) {
            // 绘制切碎的水果/炸弹
            g.setColor(new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha));
            g.fillOval(x - size/4, y - size/4, size/2, size/2);
            g.fillOval(x + size/4, y - size/4, size/2, size/2);

            if (isBomb) {
                // 炸弹爆炸效果
                g.setColor(new Color(255, 69, 0, alpha));
                g.fillOval(x - size, y - size, size*2, size*2);
            }
        } else {
            // 绘制完整水果/炸弹
            g.setColor(color);
            g.fillOval(x - size/2, y - size/2, size, size);

            if (!isBomb) {
                // 水果细节
                g.setColor(new Color(0, 100, 0));
                g.fillRect(x - 2, y - size/2 - 10, 4, 10);
            } else {
                // 炸弹细节
                g.setColor(Color.RED);
                g.drawLine(x - size/4, y - size/4, x + size/4, y + size/4);
                g.drawLine(x + size/4, y - size/4, x - size/4, y + size/4);
            }
        }
    }

    public boolean contains(int px, int py) {
        int centerX = x;
        int centerY = y;
        return Math.pow(px - centerX, 2) + Math.pow(py - centerY, 2) <= Math.pow(size/2, 2);
    }

    public void slice() {
        sliced = true;
    }

    public boolean isSliced() {
        return sliced;
    }

    public boolean isOutOfScreen() {
        return y + size < 0;
    }

    public int getAlpha() {
        return alpha;
    }

    public boolean isBomb() {
        return isBomb;
    }

    public void stopThread() {
        if (movementThread != null && movementThread.isAlive()) {
            movementThread.interrupt();
        }
    }
}
